//
//  LWZ_MusicPlayViewController.m
//  MusicFM
//
//  Created by 李光耀 on 16/1/15.
//  Copyright © 2016年 LWZ. All rights reserved.
//

#import "LWZ_MusicPlayViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "LoveMusicPlayer.h"
#import "YYWebImage.h"

@interface LWZ_MusicPlayViewController ()<AVAudioPlayerDelegate, UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong)AVAudioPlayer *avAudioPlayer;
@property (nonatomic, strong)NSTimer *timer;
@property (nonatomic, strong)NSTimer *playtimer;

@property (nonatomic, assign) NSInteger iii;

@property (nonatomic, assign)BOOL playOrPause;
@property (nonatomic, assign)BOOL likeOrNO;
@property (nonatomic, assign)BOOL zhengchangORbuzhengchang;

@property (nonatomic, assign)BOOL press;

// 播放器
@property (nonatomic, strong) LoveMusicPlayer *player;

@property (nonatomic, strong)UIImageView *imagevv;

@property (nonatomic, strong) NSTimer *imgTimer;


@property (nonatomic, strong)UITableView *tableView;
//@property (nonatomic, strong)UIScrollView *scrollView;

@end

@implementation LWZ_MusicPlayViewController

static LWZ_MusicPlayViewController *single = nil;
// 单例执行 只初始化一次
+ (instancetype) shareSingleViewController {
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        //  在多线程中保证只初始化一次
        single = [[LWZ_MusicPlayViewController alloc] init];
    });
    return single;
}



- (void)viewDidLoad {
    [super viewDidLoad];
    self.silider.value = 0.0;
    
    self.silider.minimumValue = 0.0;
    self.silider.maximumValue = 1.0;
    [self.silider addTarget:self action:@selector(progressAction:) forControlEvents:UIControlEventValueChanged];
    
    
    //    控制转动头像
    self.imgTimer = [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(zhuanzhuanzhuan) userInfo:nil repeats:YES];
    //  播放
    self.playtimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(playtimergogogo) userInfo:nil repeats:YES];
    
    
    self.imagevv = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"header.jpg"]];
    [self.view addSubview:self.imagevv];
    [_imagevv mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(80);
        make.left.offset(50);
        make.width.mas_equalTo(@314);
        make.height.mas_equalTo(@314);
    }];
    _imagevv.layer.cornerRadius = 157;
    _imagevv.layer.masksToBounds = YES;
    // Do any additional setup after loading the view from its nib.
    
//    self.scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(self.view.frame.size.width / 2, 0, self.view.frame.size.width / 2, self.view.frame.size.height -64- 49)];
//    self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake([UIScreen mainScreen].bounds.size.width/2, 64, [UIScreen mainScreen].bounds.size.width, 700)];
    //    self.automaticallyAdjustsScrollViewInsets = NO;
//    self.scrollView.contentSize = CGSizeMake(self.view.frame.size.width/2, 0);
//    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(self.view.frame.size.width/2,64,self.view.frame.size.width/2,self.view.frame.size.height- 64 - 49) style:UITableViewStylePlain];
    self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    [self.view addSubview:self.tableView];

    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.view.mas_right).offset(0);
        make.width.mas_equalTo(kScreenWidth / 2);
        make.top.equalTo(self.view.mas_top).offset(64);
        make.height.mas_equalTo(400);
    }];
    self.tableView.hidden = YES;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = [UIColor clearColor];
//    [self.view addSubview:self.scrollView];



    
    
    

    self.playOrPause = NO;
    self.likeOrNO = NO;
    self.zhengchangORbuzhengchang = NO;
    
    [self creatMusic];
}
- (IBAction)playButton:(id)sender {
    
    if (self.playOrPause) {
        [self.buttonPlay setTitle:@"暂停" forState:UIControlStateNormal];
        [self play];
    }else{
        [self.buttonPlay setTitle:@"播放" forState:UIControlStateNormal];
        [self pause];
    }
    self.playOrPause =!self.playOrPause;

}
- (IBAction)moshiButton:(id)sender {
    if (self.zhengchangORbuzhengchang) {
        [self.button_moshi setTitle:@"正常" forState:UIControlStateNormal];
        
    }else{
        [self.button_moshi setTitle:@"随机" forState:UIControlStateNormal];
        
    }
    self.zhengchangORbuzhengchang =!self.zhengchangORbuzhengchang;
}
- (IBAction)likeButton:(id)sender {
    
    if (self.likeOrNO) {
        [self.button_like setTitle:@"不喜欢" forState:UIControlStateNormal];

    }else{
        [self.button_like setTitle:@"喜欢" forState:UIControlStateNormal];

    }
    self.likeOrNO =!self.likeOrNO;
}
- (IBAction)liebiaoButton:(id)sender {
    if (_press) {
        
//        CATransition *animation = [CATransition animation];
//        animation.duration = 1.5;
//        [animation setType:@"rippleEffect"];
//        animation.subtype = kCATransitionFromLeft;
//        [self.scrollView.layer addAnimation:animation forKey:nil];
//        [_scrollView setContentOffset:CGPointMake(self.view.frame.size.width, 0) animated:NO];
        
        self.tableView.hidden = YES;
        
    }else{
        self.tableView.hidden = NO;
//        CATransition *animation = [CATransition animation];
//        
//#warning 动画
//        animation.duration = 1.5;
//        
//        [animation setType:@"rippleEffect"];
//        animation.subtype = kCATransitionPush;
//        [self.scrollView.layer addAnimation:animation forKey:nil];
//        [_scrollView setContentOffset:CGPointMake(self.view.frame.size.width/2, 0) animated:NO];
//        
//        [self.view bringSubviewToFront:self.scrollView];
    }
    _press = !_press;

    
}
- (IBAction)shangyiqu:(id)sender {
    if (!self.zhengchangORbuzhengchang) {
        for (int i = 0; i<_arraySource.count; i++) {
            if ([_strurl isEqualToString:_arraySource[i][@"url"]]) {
                self.iii = i;
                break;
            }
        }
        NSLog(@"正常上一曲");
        if (self.iii  >= 1 ) {
            self.strurl = _arraySource[_iii - 1][@"url"];
            [self creatMusic];
        }else{
            UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"通知" message:@"没有了" delegate:self cancelButtonTitle:@"我知道了" otherButtonTitles:nil, nil];
            alertView.alertViewStyle = UIAlertViewStyleDefault;
            [alertView show];
            alertView.cancelButtonIndex = 1;
            
        }
        
    }else{
        NSInteger aa = arc4random()%_arraySource.count;
        NSLog(@"%ld",aa);
        //    NSString *str = _arraySource[aa];
        NSLog(@"随机上一曲");
        self.strurl = _arraySource[aa][@"url"];
        [self creatMusic];
    }

}
- (IBAction)nextButton:(id)sender {
    if (!self.zhengchangORbuzhengchang) {
        for (int i = 0; i<_arraySource.count; i++) {
            if ([_strurl isEqualToString:_arraySource[i][@"url"]]) {
                self.iii = i;
                break;
            }
        }
        NSLog(@"正常下一曲");
        if (self.iii + 2 <= self.arraySource.count ) {
            self.strurl = _arraySource[_iii+1][@"url"];
            [self creatMusic];
        }else{
            UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"通知" message:@"没有了" delegate:self cancelButtonTitle:@"我知道了" otherButtonTitles:nil, nil];
            alertView.alertViewStyle = UIAlertViewStyleDefault;
            [alertView show];
            alertView.cancelButtonIndex = 1;

        }
        
    }else{
        NSInteger aa = arc4random()%_arraySource.count;
        NSLog(@"%ld",aa);
        //    NSString *str = _arraySource[aa];
        NSLog(@"随机下一曲");
        self.strurl = _arraySource[aa][@"url"];
        [self creatMusic];
    }

   
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated{
    for (int i = 0; i<_arraySource.count; i++) {
        if ([_strurl isEqualToString:_arraySource[i][@"url"]]) {
            self.iii = i;
            break;
        }
    }
    [self.imagevv yy_setImageWithURL:_arraySource[_iii][@"albumImg"] placeholder:[UIImage imageNamed:@"header"]];
    
}



- (void)creatMusic{

    for (int i = 0; i<_arraySource.count; i++) {
        if ([self.strurl isEqualToString:_arraySource[i][@"url"]]) {
            self.iii = i;
            break;
        }
    }
    dispatch_async(dispatch_get_main_queue(), ^{
        
            [self.imagevv yy_setImageWithURL:_arraySource[_iii][@"singerImg"] placeholder:[UIImage imageNamed:@"header"]];
        NSLog(@"%@", _arraySource[_iii][@"singerImg"]);
        NSLog(@"%ld", _iii);
        
    });
    
    

    NSString *bofangurl = [self.strurl stringByAppendingString:@"&ua=Iphone_Sst&version=4.2421&netType=1&toneFlag=1"];
    
    //创建音乐播放器对象
    self.player = [LoveMusicPlayer sharePlayer];
    [self.player playWithURL:bofangurl];
    NSLog(@"%@", _strurl);
    [self.player play];
    
}

- (void)play{
    [self.player play];
}

- (void)pause{
    [self.player pause];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"uitableViewcellidentifier"];
    cell.textLabel.text = _arraySource[indexPath.row][@"title"];

    cell.backgroundColor = [UIColor colorWithRed:135/255.0 green:206/255.0 blue:250/255.0 alpha:0.7];
    cell.layer.cornerRadius = 6;
    cell.layer.masksToBounds = YES;
#warning 取消cell点击颜色
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    return _arraySource.count;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    self.strurl = _arraySource[indexPath.row][@"url"];
    [self creatMusic];
}

- (void)zhuanzhuanzhuan{

    self.imagevv.transform = CGAffineTransformRotate(self.imagevv.transform, 0.01);
        
    
}
#pragma mark - 进度条方法
-(void)progressAction:(UISlider *)slider{


    [self.player pause];
    float current = slider.value;
    float nextCurrent = current * CMTimeGetSeconds(self.player.currentItem.duration);
    [self.player seekToTime:CMTimeMakeWithSeconds(nextCurrent, 1.0)];
    
    [self.player play];
}


-(void)playtimergogogo{
    self.silider.value=CMTimeGetSeconds(self.player.currentItem.currentTime) / CMTimeGetSeconds(self.player.currentItem.duration);
    
}






/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
